<?php


namespace App\Http\Controllers\Backend1;


use App\Http\Requests\Backend\CompanyMenuRequest;
use App\Services\Company\Models\CompanyMenu;


class CompanyMenuController extends BaseController
{


    public function tree()
    {

        $items = CompanyMenu::all()->toArray();
        $menus = $this->buildTree($items, 0);
        return  $this->successData(compact('menus'));

    }

    function buildTree(array $items, ?int $parentId = null): array
    {
        $tree = [];

        foreach ($items as $item) {
            if ($item['parent_id'] === $parentId) {
                $children = $this->buildTree($items, $item['id']);
                if ($children) {
                    $item['children'] = $children;
                }
                $tree[] = $item;
            }
        }

        return $tree;
    }

    public function store(CompanyMenuRequest $request, CompanyMenu $CompanyMenu)
    {
        $CompanyMenu->fill($request->filldata())->save();
        return $this->success(__('插入菜单成功'));

    }


    public function edit($id)

    {
        $menu= CompanyMenu::query()->where('id', $id)->firstOrFail();

        return $this->successData(compact('menu'));
    }

    public function update(CompanyMenuRequest $request, $id)
    {

        $menu = CompanyMenu::query()->where('id', $id)->firstOrFail();
        $menu->fill($request->filldata())->save();
        return $this->success(__('更新菜单成功'));

    }


    public function delete($id)
    {
        $menu = CompanyMenu::find($id);
        if ($menu->children()->exists()) {
            return  $this->error(__('存在子菜单,无法删除'));
        }

        CompanyMenu::destroy($id);
        return $this->success(__('删除菜单成功'));
    }


}
